package xyz.riceball.security.authentication;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import xyz.riceball.framework.component.SpringContextHolder;
import xyz.riceball.framework.core.bean.ApiR;
import xyz.riceball.framework.core.util.RedisUtils;
import xyz.riceball.framework.core.util.TokenUtils;
import xyz.riceball.framework.properties.TokenProperties;
import xyz.riceball.security.common.SecurityConstant;
import xyz.riceball.usercore.entity.dto.LoginDTO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 身份验证返回结果处理，正常流程
 * </p>
 *
 * @author xiaovcloud
 * @since 2022/4/25 00:18
 */
@Getter
@Setter
@Slf4j
public class RiceBallAuthenticationHandler implements
        AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setStatus(HttpStatus.HTTP_OK);
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        log.info("异常权限的处理：", exception);
        if (exception instanceof AccountExpiredException) {
            response.setStatus(401);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorCodeAndMsg(401, exception.getMessage())));
        } else if (exception instanceof AuthenticationServiceException) {
            response.setStatus(403);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorCodeAndMsg(403, exception.getMessage())));
        } else {
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorMsg(exception.getMessage())));
        }

        response.getWriter().flush();
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        //1。将信息保存在UserContext中
        //2。返回登陆信息
        LoginDTO loginDTO = (LoginDTO) authentication.getCredentials();
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put(SecurityConstant.TOKEN_USER_ID, loginDTO.getUserId());
        String token = TokenUtils.generateToken(tokenMap);
        TokenProperties tokenProperties = SpringContextHolder.getBean(TokenProperties.class);
        try {
            RedisUtils.set(SecurityConstant.TOKEN_KEY + token, token, tokenProperties.getExpireTime());
            response.setStatus(HttpStatus.HTTP_OK);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.okMsgAndData("登陆成功！", token)));
        } catch (Exception e) {
            response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorMsg(e.getMessage())));
        }
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.getWriter().flush();
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        response.setStatus(HttpStatus.HTTP_OK);
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(ApiR.okMsg("成功退出！"));
        response.getWriter().flush();
    }
}